﻿using Ace.Application;
using Ace.Application.Common;
using Ace.Data;
using Ace.Entity;
using Ace.Entity.Wiki;
using Ace.Exceptions;
using Ace.IdStrategy;
using Ace.Security;
using Chloe;
using Chloe.MySql;
using Chloe.SqlServer;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ace.Application.Wiki
{
    public interface IUsersService : IAppService
    {

        Users GetModelByMobile(string Mobile);


        List<Users> GetList(int ShopID = 0, int RoleID = 0, string keyword = "");
        Users Add(AddUsersInput input);
        void Update(UpdateUsersInput input);
        void Delete(string id );

        Users GetModel(string Id);
        Users GetModelByOpenID(string OpenID);

        PagedData<Users> GetPageData(Pagination page, int ShopID = 0, int RoleID = 0, string keyword = "", int ST = -1);




        void SetUserPass(string UserPass, string UserID);



        bool CheckMobile(string Mobile);
        bool CheckOpenID(string OpenID);

        void UpdateUserInfo(string OpenID, string Mobile, string UserIcon, string UserName);


        void UpdateUserRole(string Id, int RoleID, string transaction_id = "", string out_trade_no = "", int Days = 0);
        void UpdateReFundStatu(string Id, string out_refund_no, string out_refund_status);
    }

    public class UsersService : AppServiceBase<Users>, IUsersService
    {
        public UsersService(IDbContext dbContext, IServiceProvider services) : base(dbContext, services)
        {
        }


        public Users GetModelByMobile(string Mobile)
        {
            return this.Query.Where(a => a.Mobile == Mobile).FirstOrDefault();
        }

         


        public List<Users> GetList(int ShopID=0, int RoleID = 0, string keyword = "")
        {
            var q = this.Query;

            if (ShopID > 0)
            {
                q = q.Where(a => a.RoleID== ShopID);
            }

            if (RoleID > 0)
            {
                q = q.Where(a => a.RoleID == RoleID);
            }

            if (keyword.IsNotNullOrEmpty())
            {
                q = q.Where(a => a.Mobile.Contains(keyword));
            }

            var ret = q.ToList();
            return ret;
        }

        void Trim(AddUsersInput input)
        {
            if (input.UserName.IsNotNullOrEmpty())
                input.UserName = input.UserName.Trim();
            if (input.Mobile.IsNotNullOrEmpty())
                input.Mobile = input.Mobile.Trim();
             
        }

        public Users Add(AddUsersInput input)
        {
            //this.InsertFromDto(input);
            this.Trim(input);

            input.Validate();

            //if (input.UserName.IsNullOrEmpty() && input.Mobile.IsNullOrEmpty() && input.Email.IsNullOrEmpty())
            //{
            //    throw new InvalidInputException("用户名/手机号码/邮箱至少填一个");
            //}

            //string userName = null;
            //if (input.UserName.IsNotNullOrEmpty())
            //{
            //    userName = input.UserName.ToLower();
            //    AceUtils.EnsureAccountNameLegal(userName);
            //    bool exists = this.DbContext.Query<Users>().Where(a => a.UserName == userName).Any();
            //    if (exists)
            //        throw new InvalidInputException("用户名[{0}]已存在".ToFormat(input.UserName));
            //}

            //string mobilePhone = null;
            //if (input.Mobile.IsNotNullOrEmpty())
            //{
            //    mobilePhone = input.Mobile;
            //    if (AceUtils.IsMobilePhone(mobilePhone) == false)
            //        throw new InvalidInputException("请输入正确的手机号码");

            //    bool exists = this.DbContext.Query<Users>().Where(a => a.Mobile == mobilePhone).Any();
            //    if (exists)
            //        throw new InvalidInputException("手机号码[{0}]已存在".ToFormat(mobilePhone));
            //}

            //string email = null;
            //if (input.Email.IsNotNullOrEmpty())
            //{
            //    email = input.Email.ToLower();
            //    if (AceUtils.IsEmail(email) == false)
            //        throw new InvalidInputException("请输入正确的邮箱地址");

            //    bool exists = this.DbContext.Query<Users>().Where(a => a.Email == email).Any();
            //    if (exists)
            //        throw new InvalidInputException("邮箱地址[{0}]已存在".ToFormat(input.Email));
            //}
            
            Users user = new Users ();
            user.CreateDate = DateTime.Now;            
            user.FromID =input.FromID;            
            user.Mobile = input.Mobile;
            user.RoleID = 0;            
            user.ST = 0;
            user.UserName = input.UserName;            
            user.OpenID = input.OpenID;
            user.ShopID = input.ShopID;
            user.UserIcon = input.UserIcon;

            user.TrueName = input.TrueName;
            user.ProvinceID = input.ProvinceID;
            user.CityID = input.CityID;
            user.PartID = input.PartID;
            user.CompanyName = input.CompanyName;
            user.Service = input.Service;
            user.Job = input.Job;
            user.Tel = input.Tel;
            user.Code = input.Code;
            user.Address = input.Address;

            user.Id= IdHelper.CreateStringSnowflakeId();
            return this.DbContext.Insert(user);
        }
        public void Update(UpdateUsersInput input)
        {
            this.UpdateFromDto(input);
        }

        public Users GetModelByOpenID(string OpenID)
        {
            return  this.Query.Where(a => a.OpenID == OpenID).FirstOrDefault();
        }

        public Users GetModel(string Id)
        {
            string sql = " SELECT * FROM users WHERE Id='"+Id+"' limit 1";

            Users users = this.DbContext.SqlQuery<Users>(sql).FirstOrDefault();
            return users;
        }

        public void Delete(string id)
        {
            this.DbContext.Delete<Users>(a => a.Id == id);
        }


        public PagedData<Users> GetPageData(Pagination page,int ShopID=0, int RoleID = 0, string keyword="",int ST=-1)
        {
            var q = this.DbContext.Query<Users>();

            if (ShopID > 0)
            {
                q = q.Where(a => a.RoleID == ShopID);
            }

            if (ST > -1)
            {
                q = q.Where(a => a.ST == ST);
            }

            if (RoleID > 0)
            {
                q = q.Where(a => a.RoleID == RoleID);
            }

            q = q.WhereIfNotNullOrEmpty(keyword, a => a.Mobile.Contains(keyword) );
            q = q.OrderByDesc(a=>a.CreateDate);
            PagedData<Users> pagedData = q.TakePageData(page);
            
            return pagedData;
        }


        //----前台用户功能---------------------------------------------------------------------------------------------

        

        public bool CheckMobile(string Mobile)
        {
            return this.Query.Any(a => a.Mobile == Mobile);
        }

        public bool CheckOpenID(string OpenID)
        {
            return this.Query.Any(a => a.OpenID == OpenID);
        }


        public void UpdateUserInfo(string OpenID,string Mobile,string UserIcon,string UserName)
        {
            this.DbContext.Update<Users>(a => a.OpenID == OpenID, a => new Users()
            {
                Mobile = Mobile,
                UserIcon = UserIcon,
                UserName= UserName
            });
        }


        public void SetUserPass(string UserPass,string UserID)
        {
            this.DbContext.Update<Users>(a => a.Id == UserID, a => new Users()
            {
                UserPass = UserPass
            });
        }

        public void UpdateUserRole(string Id, int RoleID, string transaction_id = "", string out_trade_no = "",int Days=0)
        {
            this.DbContext.Update<Users>(a => a.Id == Id, a => new Users()
            {
                RoleID = RoleID
            });

            if(!string.IsNullOrEmpty(transaction_id))
            {
                this.DbContext.Update<Users>(a => a.Id == Id, a => new Users()
                {
                    transaction_id = transaction_id
                });
            }

            if (!string.IsNullOrEmpty(out_trade_no))
            {
                this.DbContext.Update<Users>(a => a.Id == Id, a => new Users()
                {
                    out_trade_no = out_trade_no
                });
            }

            if(Days>0)
            {
                this.DbContext.Update<Users>(a => a.Id == Id, a => new Users()
                {
                    RoleDate = DateTime.Now.AddDays(Days)
                });
            }
        }


        public void UpdateReFundStatu(string Id, string out_refund_no, string out_refund_status)
        {
            if (!string.IsNullOrEmpty(out_refund_no))
            {
                this.DbContext.Update<Users>(a => a.Id == Id, a => new Users()
                {
                    out_refund_no = out_refund_no
                });
            }

            if (!string.IsNullOrEmpty(out_refund_status))
            {
                this.DbContext.Update<Users>(a => a.out_trade_no == Id, a => new Users()
                {
                    out_refund_status = out_refund_status
                });
            }
        }


    }

}
